import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:waterfall_flow/waterfall_flow.dart';

import '../../EcyRouter.dart';
import '../../ecycommon/EcyCommonWidgets.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyLogger.dart';
import '../../model/EcyApiCommonPage.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../group/model/ValleyCirclePost.dart';

class EcyMyGroupDraftListPage extends EcyCommonBaseWidget {
  late _EcyMyGroupDraftListPageState state;

  EcyMyGroupDraftListPage();

  @override
  State<EcyCommonBaseWidget> createState() {
    state = _EcyMyGroupDraftListPageState();
    return state;
  }
}

class _EcyMyGroupDraftListPageState extends EcyCommonBaseWidgetState {
  _EcyMyGroupDraftListPageState();

  final ScrollController _scrollController = ScrollController();

  final List<int> indexList = List.filled(19, 0);
  List<ValleyCirclePost> _valleyCirclePostList = [];
  int _total = 0;
  int _page = 1;
  int _totalSize = 0;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _refreshData("");
  }

  void _onScroll() {
    if (_page < _total) {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _refreshData("", page: ++_page); // 加载更多数据的函数
      }
    }
  }

  Future<void> deleteById(int? id) async {
    Map<String, dynamic> body = {
      "id": id,
    };
    var response = await EcyRequestbasemanager()
        .post("/app/api/app/valley/circle/delete", body);
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        setState(() {
          _valleyCirclePostList.removeWhere((n) => n.id == id);
          _totalSize = _totalSize - 1;
        });
        EasyLoading.showToast("删除成功", duration: const Duration(seconds: 1));
      }
    }
  }

  Future<void> _refreshData(String search, {int page = 1}) async {
    try {
      Map<String, dynamic> body = {
        "size": 20,
        "current": page,
        "title": search,
        "status": "0",
        "currentUserFlag": true,
      };
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/valley/circle/page", body);
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<ValleyCirclePost> commonPage =
              EcyApiCommonPage.fromJson(
                  response["data"], (json) => ValleyCirclePost.fromJson(json));
          _total = commonPage.pages ?? 0;
          _page = commonPage.current ?? 0;
          _totalSize = commonPage.total ?? 0;
          var valleyCirclePostList = commonPage.records ?? [];
          if (page == 1) {
            _valleyCirclePostList.clear();
          }
          setState(() {
            _valleyCirclePostList.addAll(valleyCirclePostList);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取草稿列表失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget bodyWidget;
    if (_valleyCirclePostList.isEmpty) {
      bodyWidget = RefreshIndicator(
          onRefresh: () => _refreshData("", page: 1),
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  Center(
                    child: Image.asset(
                        'assets/images/empty/ic_empty_search.png',
                        width: 200,
                        height: 200),
                  ),
                  const Text('暂无草稿',
                      style: TextStyle(fontSize: 18, color: Colors.grey)),
                ]),
          ));
    } else {
      bodyWidget = RefreshIndicator(
          onRefresh: () => _refreshData("", page: 1),
          child: WaterfallFlow.builder(
              controller: _scrollController,
              physics: const AlwaysScrollableScrollPhysics(),
              gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 8.w,
                mainAxisSpacing: 8.w,
              ),
              itemCount: _valleyCirclePostList.length,
              itemBuilder: (BuildContext context, int index) {
                var valleyCirclePost = _valleyCirclePostList[index];
                return GestureDetector(
                    child: Wrap(
                      children: [
                        Container(
                            width:
                                (MediaQuery.of(context).size.width - 24.w) / 2,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(8.r),
                                  topRight: Radius.circular(8.r)),
                              color: Colors.white,
                            ),
                            child: CachedNetworkImage(
                                width:
                                    (MediaQuery.of(context).size.width - 24.w) /
                                        2,
                                height: 176.w,
                                imageUrl: valleyCirclePost.mainImage ?? "",
                                imageBuilder: (context, imageProvider) =>
                                    Container(
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.only(
                                              topRight: Radius.circular(8.r),
                                              topLeft: Radius.circular(8.r)),
                                          image: DecorationImage(
                                              image: imageProvider,
                                              fit: BoxFit.cover)),
                                    ),
                                errorWidget: (context, url, error) =>
                                    Image.asset("assets/images/app_icon.png"))),
                        Container(
                          width: (MediaQuery.of(context).size.width - 24.w) / 2,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(8.r),
                                bottomRight: Radius.circular(8.r)),
                            color: const Color(0xFFFFFFFF),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(6),
                                child: Text(
                                    valleyCirclePost.createTime
                                            ?.replaceFirst("T", " ") ??
                                        "",
                                    style: const TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 12,
                                      color: Color(0xFF8C8C8C),
                                      leadingDistribution:
                                          TextLeadingDistribution
                                              .even, // 设置leading策略
                                    )),
                              ),
                              GestureDetector(
                                behavior: HitTestBehavior.translucent,
                                child: Padding(
                                    padding: const EdgeInsets.all(6),
                                    child: Image.asset(
                                        'assets/images/ic_delete.png',
                                        width: 12)),
                                onTap: () {
                                  deleteById(valleyCirclePost.id);
                                },
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    onTap: () {
                      EcyRouter().push(context, EcyRouter.groupPublishPage, {
                        "id": valleyCirclePost.id
                      }).then((val) => val ? _refreshData("") : null);
                    });
              }));
    }
    return Scaffold(
      backgroundColor: const Color(0XFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 50.w,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            Navigator.pop(context, _totalSize);
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        titleSpacing: 0,
        centerTitle: true,
        title: Text("草稿箱($_totalSize)",
            style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w700,
                fontSize: 16.sp,
                color: const Color(0xFF262626))),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8),
        child: bodyWidget,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  void deactivate() {
    super.deactivate();
  }
}
